import remoteLoad from "./remoteLoad";
import { addressInfo, getAddress } from "./getMapData";
import store from "/@/store/index";
import { Toast } from "vant";

// 高德地图 key
export const MapKey = "cfd8da5cf010c5f7441834ff5e764f5b";
// 地图限定城市
export const MapCityName = "北京";
// 地图中心点
export const MapCenterPositon = [116.397428, 39.90923];

// 创建地图实例
export const initMapSmall = (container, position, options, mapLoadSuccess) => {
  return new Promise((resolve, reject) => {
    createdMapApi(AMap => {
      const mapConfig = {
        zoom: 14, // 初始地图级别
        center: position && position.length === 2 ? position : MapCenterPositon, // 初始地图中心点
        animateEnable: false, // 地图平移过程中是否使用动画
        cursor: "grab", // 设置鼠标样式
        isHotspot: false
      };
      // 创建小地图实例
      const map = new AMap.Map(container, mapConfig);
      window.MAPINSTANCE = map;
      // 添加地图控件
      mapControls(map, options);
      // 加载完成回调
      map.on("complete", res => {
        if (res.type === "complete") {
          // 加载UI组件
          loadAMapUI(
            AMapUI => {
              resolve({ AMap, AMapUI, map });
            },
            () => {
              // 加载UI组件异常
              reject({
                message: "加载UI组件异常"
              });
            }
          );
        } else {
          reject({
            message: "加载地图组件异常"
          });
        }
      });
    }),
      () => {
        reject({
          message: "加载地图组件异常"
        });
      };
  });
};
let mineMarker;
export function getLocationCity(call) {
  try {
    JSBridge.call("getCurrentLocation", "", data => {
      const lnglat = {
        lat: data.latitude,
        lng: data.longitude
      };
      setMine(lnglat, call);
      call && call();
    });
  } catch (e) {
    call && call();
    Toast("定位失败");
  }
}
function setMine(data) {
  try {
    mineMarker &&
      window.MAPINSTANCE &&
      window.MAPINSTANCE.remove &&
      window.MAPINSTANCE.remove(mineMarker);
    mineMarker = new window.AMap.Marker({
      position: new window.AMap.LngLat(data.lng, data.lat),
      content:
        '<img src="https://a.amap.com/jsapi_demos/static/resource/img/user.png" style="width:36px;height:36px"/>',
      map: window.MAPINSTANCE
    });
    // 调整视野达到最佳显示区域
    window.MAPINSTANCE.setFitView([mineMarker]);
  } catch (e) {
    Toast("定位失败");
  }
}

// 添加地图控件
export const mapControls = (map, opt = {}) => {
  // 比例尺
  window.AMap.plugin(["AMap.Scale"], () => {
    map.addControl(
      new window.AMap.Scale({
        position: "LB"
      })
    );
  });
  if (!opt.noMinePos) {
    if (sessionStorage.isNative == "1") {
      getLocationCity();
    } else {
      window.AMap.plugin("AMap.Geolocation", function() {
        const geolocation = new window.AMap.Geolocation({
          enableHighAccuracy: true, //是否使用高精度定位，默认:true
          buttonPosition: "RB", //定位按钮的停靠位置
          timeout: 10000,
          noIpLocate: "1",
          noGeoLocation: "1",
          GeoLocationFirst: true,
          showCircle: false,
          buttonOffset: new window.AMap.Pixel(10, 20), //定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
          useNative: true,
          panToLocation: true,
          zoomToAccuracy: true,
          markerOptions: {
            //自定义定位点样式，同Marker的Options
            offset: new window.AMap.Pixel(-18, -36),
            content:
              '<img src="https://a.amap.com/jsapi_demos/static/resource/img/user.png" style="width:36px;height:36px"/>'
          }
        });
        map.addControl(geolocation);
        window.GETMINEADDRESS = geolocation;
        // 获取我的位置的经纬度
        getAddress(citys => {
          window.DEFAULTADDRESS = citys;
        });
      });
    }
  }
  // 添加地图（经纬度和地址）转换组件
  window.AMap.plugin("AMap.Geocoder", function() {});
  // 加载搜索组件
  window.AMap.plugin("AMap.PlaceSearch", () => {});
  // 加载地图绘制组件
  window.AMap.plugin("AMap.Driving", () => {});
};

// 载入高德地图API
export const createdMapApi = async (success, fail) => {
  if (!window.AMap) {
    window.onAMapLoaded = function() {
      if (window.AMap) {
        success(window.AMap);
      } else {
        fail();
      }
    };
    await remoteLoad(
      `https://webapi.amap.com/maps?v=2.0&key=${MapKey}&callback=onAMapLoaded`
    );
  } else {
    success(window.AMap);
  }
};
// 加载高德地图UI
export const loadAMapUI = async (success, fail) => {
  if (!window.AMapUI) {
    await remoteLoad("https://webapi.amap.com/ui/1.1/main.js");
    // await remoteLoad("https://webapi.amap.com/ui/1.1/main-async.js");
    if (window.AMapUI) {
      success(window.AMapUI);
    } else {
      fail();
    }
  }
  success(window.AMapUI);
};
